package com.lawliet.example.handler.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lawliet.example.model.system.SysUser;
import com.lawliet.example.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * DAO 层操作过程中的钩子
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
 
   @Override
   public void insertFill(MetaObject metaObject) {
      try {
         SysUser loginUser = Utils.getLoginUser();
         if(loginUser!=null){
            if (metaObject.hasGetter("createBy")) {
               this.setFieldValByName("createBy",loginUser.getId(), metaObject);
            }
         }
         //根据属性的名字加入判断即可
         if (metaObject.hasGetter("createTime")) {
            this.setFieldValByName("createTime", new Date(), metaObject);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      updateFill(metaObject);
   }
 
   @Override
   public void updateFill(MetaObject metaObject) {
      try {
         SysUser loginUser = Utils.getLoginUser();
         if(loginUser!=null){
            if (metaObject.hasGetter("updateBy")) {
               this.setFieldValByName("updateBy",loginUser.getId(), metaObject);
            }
         }
         if (metaObject.hasGetter("updateTime")) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
 
}